/**
 * 用于commits页面将path解析为面包屑
 */

import React from 'react';
import { Breadcrumb } from '@teamix/ui';
import PropTypes from 'prop-types';
import { navigate } from 'utils/router';
import utils from 'utils';
import './index.scss';

const { pathResource, resourceSubject } = window.FORCE;

export default class PathBreadcrumb extends React.Component {
  static propTypes = {
    resourcePath: PropTypes.string,
  };

  static defaultProps = {
    resourcePath: '',
  };

  getBreadList = () => {
    const { resourcePath } = this.props;
    const { fullPath } = pathResource;
    const projectName = fullPath.split('/')[1];
    const list = [
      {
        name: projectName,
        path: `/${fullPath}`,
      },
    ];
    // 根路径显示表格时
    const pathArr = resourcePath === '/' ? [] : resourcePath.split('/');
    let sumPath = '';
    pathArr.forEach((item) => {
      sumPath += `/${item}`;
      list.push({
        path: `/${pathResource.fullPath}/commits/${utils.revisionEncodeURI(
          resourceSubject.revision,
        )}${sumPath}`,
        name: item,
        resourcePath: sumPath,
      });
    });
    return list;
  };

  handleClick = (path) => {
    if (path) {
      navigate(
        `/${pathResource.fullPath}/commits/${utils.revisionEncodeURI(
          resourceSubject.revision,
        )}${path}`,
        {
          state: { forceUpdate: true },
        },
      );
    } else {
      navigate(
        `/${pathResource.fullPath}/commits/${utils.revisionEncodeURI(resourceSubject.revision)}`,
        {
          state: { forceUpdate: true },
        },
      );
    }
  };

  render() {
    const breadList = this.getBreadList();
    return (
      <React.Fragment>
        <Breadcrumb className="code-breadcrumb" separator={'/'}>
          {breadList.map((item, index) => {
            if (index === breadList.length - 1) {
              return <Breadcrumb.Item key={item.path}>{item.name}</Breadcrumb.Item>;
            }
            return (
              <Breadcrumb.Item
                onClick={() => {
                  this.handleClick(item.resourcePath);
                }}
                key={item.path}
                className="breadcrumb-not-last"
                style={{ cursor: 'pointer' }}
              >
                {item.name}
              </Breadcrumb.Item>
            );
          })}
        </Breadcrumb>
      </React.Fragment>
    );
  }
}
